package com.hxzy.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Calendar;

import org.apache.commons.lang3.StringUtils;

import com.hxzy.dao.AttachmentDao;
import com.hxzy.dao.AttachmentDaoImpl;
import com.hxzy.dao.UserDao;
import com.hxzy.dao.UserDaoImpl;
import com.hxzy.entity.Attachment;

public class UserUploadServiceImpl implements UserUploadService {

	private AttachmentDao attachmentDao=new AttachmentDaoImpl();
	private UserDao userDao=new UserDaoImpl();
	
	public String Upload(File srcFile, String contentType, File destFile,long userCreate,long userModified) {
		// TODO Auto-generated method stub
		
		FileInputStream fis=null;
		FileOutputStream fos=null;
		try {
			fis = new FileInputStream(srcFile);
			fos=new FileOutputStream(destFile);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return StringUtils.EMPTY;
		}
		
		FileChannel input=fis.getChannel();
		FileChannel ouput=fos.getChannel();
		long size=0;
		try {
			size = input.size();
			long count=0;
			int pos=0;
			int buffer_size=1024;
			while(pos<size){
				count=(size-pos)>buffer_size?buffer_size:(size-pos);
				pos+=ouput.transferFrom(fis.getChannel(),pos, count);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return StringUtils.EMPTY;
		}finally {
			try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		//FileUtils.copyFile(srcFile, destFile);
		
		
		
		AttachmentDao attachmentDao=new AttachmentDaoImpl();
		Attachment attachment=new Attachment();
		Calendar c = Calendar.getInstance();
		long now= (int) (c.getTimeInMillis() / 1000);
		attachment.setContentType(contentType);
		attachment.setFilename(destFile.getName());
		attachment.setSize(size);
		attachment.setPath(srcFile.getPath());
		attachment.setGmtCreate(now);
		attachment.setGmtCreate(now);
		attachmentDao.Upload(attachment);
		return "http://localhost:8080/struts-manager/download?id="+attachment.getId();
	}

	public AttachmentDao getAttachmentDao() {
		return attachmentDao;
	}

	public void setAttachmentDao(AttachmentDao attachmentDao) {
		this.attachmentDao = attachmentDao;
	}

	
}
